import WindowMaximize from "@/assets/svgs/window-maximize.svg?react";
import WindowRestore from "@/assets/svgs/window-restore.svg?react";
import { useTranslation } from "@/i18n";
import Icon from "@ant-design/icons";
import { ButtonProps } from "antd";
import React, { useEffect, useMemo, useState } from "react";
import { call_runtime } from "../../../utils/call_runtime";
import { TopBarIconButton } from "./TopBarIconButton";
export async function maximize(): Promise<void> { call_runtime('WindowMaximise') }
export async function unmaximize(): Promise<void> { call_runtime('WindowUnmaximise') }
export async function is_maximized(): Promise<boolean> { return call_runtime('WindowIsMaximised') ?? Promise.resolve(false) }
export async function toggle_maximize() {
  return is_maximized().then(r => r ? unmaximize() : maximize())
}
export interface IProps extends ButtonProps {
  ele?: HTMLElement | null;
}
export function MaximizeButton(props: IProps) {
  const { t } = useTranslation();
  const { ele, className, onClick, ...remain_props } = props;
  const [maximized, set_is_maximised] = useState(false)
  useEffect(() => {
    const on_resize = () => is_maximized().then(set_is_maximised)
    on_resize();
    window.addEventListener('resize', () => on_resize());
    return () => window.removeEventListener('resize', on_resize);
  }, [])

  const title = useMemo(() => maximized ? t('common.unmaximize') : t('common.maximize'), [maximized])
  const icon = <Icon component={maximized ? WindowRestore : WindowMaximize} />
  const on_click = (e: React.MouseEvent<HTMLElement>) => {
    is_maximized().then(r => r ? unmaximize() : maximize())
  }
  return (
    <TopBarIconButton
      className={className}
      title={title}
      onClick={on_click}
      {...remain_props}>
      {icon}
    </TopBarIconButton>
  )
}